using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using AutoUpdateEngine.Commands;
using AutoUpdateEngine.Commands.XmlObjects;
using AutoUpdateEngine.Operations;
using log4net;
namespace AutoUpdateEngine.Xml
{
    public class XMLPaser
    {
        public XMLPaser(string updatesXml)
        {
            doc = new XPathDocument(updatesXml);
            xpathNav = doc.CreateNavigator();
        }

        public ILog Logger
        {
            get { return logger; }
            set { logger = value; }
        }

        /// <summary>
        /// get all the updating operations
        /// </summary>
        /// <returns></returns>
        public IList<IOperation> GetOperations()
        {
            //select all the operation elements
            XPathNodeIterator operationNodeIterator = xpathNav.Select("/updates/operation");
            IList<IOperation> operations = new List<IOperation>(operationNodeIterator.Count);
            //build an Operation instance for each operation element
            while (operationNodeIterator.MoveNext())
            {
                IOperation op = new OperationBuilder(operationNodeIterator.Current).Build();
                operations.Add(op);
            }
            return operations;
        }

        XPathNavigator xpathNav;
        XPathDocument doc;

        public XMLPaser()
        {
            
        }

        private ILog logger;

        public IList<ICommand> GetCommands()
        {
            IList<ICommand> commands = new List<ICommand>();


            return commands;
        }

        public XmlDocument ReadXml(string fileName)
        {
            if (!File.Exists(fileName))
                throw new FileNotFoundException();

            XmlDocument xmlDoc=new XmlDocument();
            xmlDoc.Load(fileName);

            return xmlDoc;
        }

        public void ParseDocument(XmlDocument xmlDocument)
        {
            //xmlDocument.Validate(new ValidationEventHandler(ValidateXmlDocument));
            ICommandXmlObject cxobject;
            string createExpression = "/updates/create";
            XPathNavigator xnav = xmlDocument.CreateNavigator();
            XPathNodeIterator iterator = xnav.Select(createExpression);
            while(iterator.MoveNext())
            {
               
            }
        }
       
        private void ValidateXmlDocument(object sender, ValidationEventArgs e)
        {
            if (e.Exception != null)
            {
                if(logger!=null)
                    logger.Error(e.Message,e.Exception);
                throw e.Exception;
            }
        }
    }
}
